import '../../scss/interface.scss'
import React from 'react'
import {config as baseConfig, name as baseConfigName} from '../../config/request/base'
import {Client} from '../../module/client'

export default React.createClass({
    render() {
        return <div id='interface'>
            <List config={baseConfig}/>
        </div>
    }
})

class Item extends React.Component {
    submit(e) {
        e.stopPropagation()
        e.preventDefault()
        let config = this.props.config
        let data = {}
        for (let i in config.input) {
            if (config.input[i].type === 'number') {
                data[i] = Number(this.refs[i].value)
            } else {
                data[i] = this.refs[i].value
            }
        }
        for (let i in config.select) {
            if (config.select[i].type === 'number') {
                data[i] = Number(this.refs[i].value)
            } else {
                data[i] = this.refs[i].value
            }
        }
        window.client.request(config.router, data)
    }

    render() {
        let config = this.props.config
        let inputNode = [];
        for (let i in config.input) {
            let item = config.input[i]
            let type = 'text'
            if (item.type === 'number') {
                type = 'number'
            }
            let node = (
                <div key={i}>
                    <div>
                        <span className="name">
                            {i}</span>
                        <span className="prompt">
                            {item.prompt}</span>
                    </div>
                    <div><input name={i} ref={i} type={type}/></div>
                </div>
            )
            inputNode.push(node)
        }
        return (
            <form className="item" onSubmit={this.submit.bind(this)}>
                <div className="title">{config.title}{config.router}</div>
                {inputNode}
                <button className="button">确定</button>
            </form>
        )
    }
}

class List extends React.Component {
    disconnect() {
        if (window.client) {
            window.client.disconnect()
        }
        let client = new Client()
        client.init({ip: '127.0.0.1', port: 12345})
        window.client = client
    }
    render() {
        let self = this,
            config = this.props.config,
            node = config.map(function(item, i) {
                return <Item config={item} key={i}/>
            })
        return <div className="flex wrap box">
            <div className="item">
                <button className="button" onClick={this.disconnect}>重新连接</button>
            </div>{node}
        </div>
    }
}
